package data

import (
	"fmt"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
)

type InvoiceAddrDto struct {
	Id        int    `orm:"pk;auto;column(id)"`
	MemberId  int    `orm:"column(member_id)"`
	Title     string `orm:"column(title)"`
	Addr      string `orm:"column(addr)"`
	RecvName  string `orm:"column(recv_name)"`
	ZipCode   string `orm:"column(zip_code)"`
	RecvPhone string `orm:"column(recv_phone)"`
	TaxNo     string `orm:"column(tax_no)"`
}

type InvoiceInfoDto struct {
	Id          int     `orm:"pk;auto;column(id)"`
	Title       string  `orm:"column(title)"`
	Addr        string  `orm:"column(addr)"`
	RecvName    string  `orm:"column(recv_name)"`
	ZipCode     string  `orm:"column(zip_code)"`
	RecvPhone   string  `orm:"column(recv_phone)"`
	TaxNo       string  `orm:"column(tax_no)"`
	Amount      float32 `orm:"column(amount)"`
	InvoiceCorp string  `orm:"column(invoice_corp)"`
}

func init() {
	orm.RegisterModel(new(InvoiceAddrDto))
}

func (c *InvoiceAddrDto) TableName() string {
	return "l_invoice_addr"
}

func (l LogisticsRepo) GetInvoiceAddrs(mbrId int) ([]InvoiceAddrDto, error) {
	var list []InvoiceAddrDto
	o := orm.NewOrm()
	_, err := o.Raw(SQL_Logis_Get_Invoice_Addrs, mbrId).QueryRows(&list)
	return list, err
}

func (l LogisticsRepo) EnsureInvoiceCorpExists(invoiceCorpId int) bool {
	var list orm.ParamsList
	o := orm.NewOrm()
	num, _ := o.Raw(SQL_Logis_Ensure_Invoice_Corp_Exists, invoiceCorpId).ValuesFlat(&list)
	return num > 0
}

func (l LogisticsRepo) AddInvoiceAddr(dto *InvoiceAddrDto) (id int64, err error) {
	var addrs []InvoiceAddrDto
	addrs, err = l.GetInvoiceAddrs(dto.MemberId)
	if len(addrs) < 3 {
		o := orm.NewOrm()
		id, err = o.Insert(dto)
	} else {
		err = fmt.Errorf("too many invoice addrs")
	}
	return
}

func (l LogisticsRepo) UpdateInvoiceAddr(mbrId int, dto *InvoiceAddrDto) error {
	o := orm.NewOrm()
	_, err := o.Raw(SQL_Logis_Update_Invoice_Addr, dto.Title, dto.Addr, dto.RecvName, dto.RecvPhone, dto.ZipCode, dto.TaxNo, dto.Id, mbrId).Exec()
	return err
}

func (l LogisticsRepo) DeleteInvoiceAddr(mbrId, invoiceAddrId int) error {
	o := orm.NewOrm()
	_, err := o.Raw(SQL_Logis_Delete_Invoice_Addr, invoiceAddrId, mbrId).Exec()
	return err
}

func (l LogisticsRepo) GetInvoiceAddr(invoiceAddrId int) (InvoiceAddrDto, error) {
	dto := InvoiceAddrDto{Id: invoiceAddrId}
	o := orm.NewOrm()
	err := o.Read(&dto)
	return dto, err
}

func (l LogisticsRepo) GetLastInvoiceAddr(mbrId int) (invoiceAddr InvoiceAddrDto, err error) {
	o := orm.NewOrm()
	if err = o.Raw(SQL_Logis_Get_Last_Invoice_Addr_1, mbrId).QueryRow(&invoiceAddr); err != nil {
		err = o.Raw(SQL_Logis_Get_Last_Invoice_Addr_2, mbrId).QueryRow(&invoiceAddr)
	}
	return invoiceAddr, err
}

func (l LogisticsRepo) GetInvoiceInfo(waybillId int) (info InvoiceInfoDto, err error) {
	o := orm.NewOrm()
	err = o.Raw(SQL_Order_Get_Invoice_Info, waybillId).QueryRow(&info)
	return
}
